package com.game.thrones.Interceptor;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.game.thrones.constant.Constants;
import com.game.thrones.constant.Errors;
import com.game.thrones.controller.KbmThreadLocal;
import com.game.thrones.controller.output.ResultResponseBeanUtil;
//import com.game.thrones.controller.role.RolePermissionOutput;
import com.game.thrones.domain.KbmContent;
//import com.game.thrones.domain.permission.ResourceDO;
//import com.game.thrones.domain.role.UserRoleDO;
//import com.game.thrones.domain.user.UserDO;
//import com.game.thrones.service.permission.ResourceService;
//import com.game.thrones.service.role.RolePermissionService;
//import com.game.thrones.service.role.UserRoleService;
//import com.game.thrones.util.JedisUtil;
import com.game.thrones.util.JsonUtil;
import com.game.thrones.util.StringUtils;

public class UserSecurityInterceptor implements HandlerInterceptor {
	private Logger log = LoggerFactory.getLogger(getClass());
//	@Autowired
//	private UserRoleService userRoleService;
//	@Autowired
//	private RolePermissionService rolePermissionService;
//	@Autowired
//	private ResourceService resourceService;

	private static Set<String> excludesInteceptUrlSet = null;// 这几个url不做权限控制
	static {
		excludesInteceptUrlSet = new HashSet<String>();
		excludesInteceptUrlSet.add("/thrones/api/v1/user/login");
		excludesInteceptUrlSet.add("/thrones/api/v1/user/logout");
		excludesInteceptUrlSet.add("/thrones/api/v1/user/getVerCode");
		excludesInteceptUrlSet.add("/thrones/api/v1/user/resetPassword");
		excludesInteceptUrlSet.add("/v2/api-docs");

		excludesInteceptUrlSet.add("/web/banner/findListByType"       );//网站-轮播图-根据类型获取banner列表
		excludesInteceptUrlSet.add("/web/banner/findOneByType"        );//网站-轮播图-根据类型获取banner
		excludesInteceptUrlSet.add("/web/news/expertTeamList"         );//网站-新闻-专家团队列表
		excludesInteceptUrlSet.add("/web/news/findListByType"         );//网站-新闻-根据类型获取列表
		excludesInteceptUrlSet.add("/web/news/findOneById"            );//网站-新闻-根据ID获取
		excludesInteceptUrlSet.add("/web/news/findOneByType"          );//网站-新闻-根据类型获取
		excludesInteceptUrlSet.add("/web/news/findPageListByType"     );//网站-新闻-分页列表(前端页面用)
		excludesInteceptUrlSet.add("/web/webApply/add"                );//网站-报名信息-新增
		excludesInteceptUrlSet.add("/web/webCourse/list"              );//网站-课程信息-列表(前端页面用)
		excludesInteceptUrlSet.add("/web/webEndemic/getDefaultEndemic");//网站-地方中心-获取默认地方中心
		excludesInteceptUrlSet.add("/web/webEndemic/list"             );//网站-地方中心-列表(网站用)
		excludesInteceptUrlSet.add("/web/webEndemic/openedList"       );//网站-地方中心-已开通列表(网站用)
		excludesInteceptUrlSet.add("/web/webJob/list"                 );//网站-招聘信息-列表(前端页面用)
	}

	/**
	 * 拦截request请求
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String systemState = "dev";

		String servletPath = request.getServletPath();
		if (servletPath.indexOf("/thrones/api/v1/errors") == 0) {
			return true;
		}
		if (servletPath.indexOf("/errors") == 0) {
			return true;
		}
		if (servletPath.indexOf("/error") == 0) {
			return true;
		}
		if (excludesInteceptUrlSet.contains(servletPath)) {// 验证权限
			return true;
		}

		log.info("请求路径:" + servletPath);
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		String ip = request.getHeader("X-Real-IP");
		String userToken = request.getHeader("USER-TOKEN");
		// 获取用户token
		Method method = handlerMethod.getMethod();
		log.info("用户:" + ip + ",访问目标:" + method.getDeclaringClass().getName());
		log.info("userToken:" + userToken);
		if (StringUtils.isBlank(userToken) && systemState.equals("dev")) {// 如果是开发环境并且userToken为空则给userToken默认值
			userToken = "testToken";
		}
//		if (resourceService == null) {
//			BeanFactory factory = WebApplicationContextUtils
//					.getRequiredWebApplicationContext(request.getServletContext());
//			resourceService = (ResourceService) factory.getBean("resourceService");
//		}



		if (StringUtils.isBlank(userToken)) {// 如果token为空则报错
			// response.setContentType("text/html;charset=utf-8");
			// response.sendRedirect("/thrones/api/v1/errors/notLogin");
			PrintWriter out = response.getWriter();
			out.print(JsonUtil.beanToJson(ResultResponseBeanUtil.fail(Errors.NOT_LOGIN)));
			return false;
		}
//		KbmContent content = (KbmContent) JedisUtil.getObj(Constants.CURRENT_SYS_USER_TOKEN + userToken);
//		if (content == null) {// 如果拿不到登录信息则报错
//			// response.setContentType("text/html;charset=utf-8");
//			// response.sendRedirect("/thrones/api/v1/errors/notLogin");
//			PrintWriter out = response.getWriter();
//			out.print(JsonUtil.beanToJson(ResultResponseBeanUtil.fail(Errors.NOT_LOGIN)));
//			return false;
//		}
//		request.getSession().setAttribute(Constants.CURRENT_SYS_USER_INFO, content);// 设置当前用户信息到缓存
//
//		String actionPath = getActionPath(servletPath);
//		ResourceDO resource = resourceService.findByPath(actionPath);// 根据路径获取资源信息
//		{
//			if (resource.getType() == 0) {// 资源白名单直接放行
//				return true;
//			}
//		}

//
//		KbmThreadLocal.setContent(content);// 设置线程上下文环境
//
//		if ("/user/getCurrentUserEndemic".equals(actionPath) || "/user/getCurrentUserInfo".equals(actionPath)
//				|| "/permission/setEndemic".equals(actionPath)
//				|| "/user/getCurrentUserSelectEndemic".equals(actionPath)) {
//			return true;
//		}
//		if (content.getEndemicId() == null) {// 判断是否选择节点中心
//			// response.setContentType("text/html;charset=utf-8");
//			// response.sendRedirect("/thrones/api/v1/errors/notEndemic");
//
//			log.error("*********************************");
//			log.error("*********************************");
//			log.error("未选择地方中心");
//			log.error("*********************************");
//			log.error("*********************************");
//
//			PrintWriter out = response.getWriter();
//			out.print(JsonUtil.beanToJson(ResultResponseBeanUtil.fail(Errors.NO_ENDEMIC)));
//			return false;
//		}
//		if (userRoleService == null) {// 解决service为null无法注入问题
//			BeanFactory factory = WebApplicationContextUtils
//					.getRequiredWebApplicationContext(request.getServletContext());
//			userRoleService = (UserRoleService) factory.getBean("userRoleService");
//		}
//		if (rolePermissionService == null) {
//			BeanFactory factory = WebApplicationContextUtils
//					.getRequiredWebApplicationContext(request.getServletContext());
//			rolePermissionService = (RolePermissionService) factory.getBean("rolePermissionService");
//		}
//
//		Integer permissionId = resource.getPermissionId();
//		if (permissionId == -1) {// 资源未配置
//			PrintWriter out = response.getWriter();
//			out.print(JsonUtil.beanToJson(ResultResponseBeanUtil.fail(Errors.TRANSFER_ENCODING_NOT_EXIST)));
//			log.error("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//			log.error("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//			log.error("路径" + actionPath + "未配置");
//			log.error("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//			log.error("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//
//			return false;
//		}
//		if (permissionId == 0) {// 登陆后可以自由访问的资源
//			return true;
//		}
//		if (content.getCategoryId() == UserDO.superUserCategory) {// 如果当前用户是系统管理员则直接允许访问接口
//			return true;
//		}
//
//		{// 权限过滤
//			List<UserRoleDO> userRoleList = userRoleService.findByEndemicIdAndUserId(content, content.getEndemicId(),
//					content.getCurrentUserId());
//			for (UserRoleDO entity : userRoleList) {
//				List<RolePermissionOutput> RolePermissionVoList = new ArrayList<RolePermissionOutput>();
//				try {
//					RolePermissionVoList = rolePermissionService.findByRoleId(content, entity.getRoleId());
//				} catch (Exception e) {
//					log.error("ID为" + entity.getRoleId() + "的角色不存在");
//				}
//
//				for (RolePermissionOutput output : RolePermissionVoList) {
//					if (permissionId.equals(output.getPermissionId())) {
//						if (output.getIsHave() == 1) {
//							return true;
//						} else {
//							if (content.getCategoryId().intValue() == UserDO.superUserCategory) {
//								return true;
//							}
//
//							// PrintWriter out = response.getWriter();
//							// out.print(JsonUtil.beanToJson(ResultResponseBeanUtil.fail(Errors.NOT_PERMISSION)));
//							// return false; 如果没有权限则继续循环
//							/*
//							 * if (content.getCategoryId() != 0) {// 如果是管理员直接放行
//							 * 暂时去掉 PrintWriter out = response.getWriter();
//							 * out.print(JsonUtil.beanToJson(
//							 * ResultResponseBeanUtil.fail(Errors.NOT_PERMISSION
//							 * ))); return false; }
//							 */
//						}
//					}
//				}
//			}
//		}
		// log.error("*********************************");
		// log.error("*********************************");
		// log.error("资源" + actionPath + "未配置权限或不存在,权限为" + permissionId);
		// log.error("*********************************");
		// log.error("*********************************");
//		PrintWriter out = response.getWriter();
//		out.print(JsonUtil.beanToJson(ResultResponseBeanUtil.fail(Errors.NOT_PERMISSION)));
		return true;
	}

	private String getActionPath(String servletPath) {
		return servletPath.substring("/thrones/api/v1".length());
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
